package com.cmpan.networkdisk.controller;

import com.cmpan.networkdisk.model.Disk;
import com.cmpan.networkdisk.service.DiskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * ClassName:UploadingController
 * Package:com.cmpan.networkdisk.controller
 * Description:
 *
 * @Date:2020/7/7 12:24
 * @com.chuangmei
 */
@Controller
@RequestMapping("/upload")
public class UploadingController {

    /*日志*/
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DiskService diskService;

    @PostMapping("/data")
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public @ResponseBody String uploadfile(MultipartFile[] files, String type, HttpSession session) throws IOException {

        //上传成功条数
        int computeSuccess = 0;

        //上传路径-本地
        String uploadPath = "G:\\uploadFile";

        //上传路径-服务器
        //String uploadPath = "/home/uploadFile";

        //file
        File file = new File(uploadPath);

        //是否已经存在
        boolean repetition = false;
        String repetitionFileName = "";

        //map
        Map map = null;

        //返回
        String result = "Failed";

       //判断路径是否存在
        if (!file.exists()){
            boolean ok = file.mkdirs();
            System.out.println(ok);
        }

        //多个上传
        for (MultipartFile nowfile : files){
            //disk
            Disk disk = new Disk();
            //如果大小大于0
            if (nowfile.getSize() > 0){
                //获取源文件名
                String name = nowfile.getOriginalFilename();
                //file
                File uploadfile = new File(file,name);
                //转换为double类型并保留两位小数
                double size = ConvertToDouble(((double)nowfile.getSize())/1024/1024);
                //date
                String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
                //封装数据
                disk.setFilename(name);
                disk.setFilepath(uploadfile.toString());
                disk.setFilesize(size);
                disk.setCreatetime(date);
                disk.setModifytime(date);
                disk.setTypeid(Long.valueOf(type));

                //调用dao层写入数据
                map = diskService.uploadFile(disk);
                int count = (Integer)map.get("count");
                //是否成功
                if (count > 0){
                    result =  "Success";
                    //上传操作
                    nowfile.transferTo(uploadfile);
                    computeSuccess++;
                }else if (count == 0){
                    repetition = true;
                    repetitionFileName += map.get("fileName") + "  ";
                }else {
                    result = "Failed";
                }
            }
        }

        //封装数据
        Updata updata = new Updata(uploadPath,files);
        //日志处理
        logger.info("updata: {}", updata);

        //此处如果直接重定向无法跳转页面,因为前端是ajax发送请求,只接受json数据
        // 可以在前台回调函数进行window.location='/xxx';跳转
        return repetition ? repetitionFileName : result;
    }

    //转换
    private double ConvertToDouble(double param) {
        return Double.valueOf(String.format("%.2f",param));
    }

    private class Updata{
        private String path;
        private MultipartFile[] files;

        public Updata(String path, MultipartFile[] files) {
            this.path = path;
            this.files = files;
        }

        @Override
        public String toString() {
            return "updata{" +
                    "path='" + path + '\'' +
                    ", files=" + Arrays.toString(files) +
                    '}';
        }
    }


}
